package com.breeze.blockchain.mybatis.entity;

import static com.breeze.blockchain.common.exception.BizErrorCode.USER_STATUS_ERROR;
import static com.breeze.blockchain.common.exception.BizErrorCode.USER_STATUS_FREEZE_ERROR;
import static com.breeze.blockchain.common.exception.BizErrorCode.USER_STATUS_LOCK_ERROR;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.breeze.components.mybatis.base.BaseEntity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.mybatisflex.annotation.Column;
import com.mybatisflex.annotation.Table;
import io.swagger.v3.oas.annotations.media.Schema;
import java.io.Serial;
import java.io.Serializable;
import java.time.LocalDateTime;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;

/**
 * 用户信息表 实体类。
 *
 * @author breeze
 * @since 2024-04-21 20:47:54
 */
@Data
@Accessors(chain = true)
@RequiredArgsConstructor
@EqualsAndHashCode(callSuper = true)
@Schema(title = "用户信息表")
@Table("sys_user")
@ToString(callSuper = true)
public class UserDo extends BaseEntity implements Serializable {

  @Serial private static final long serialVersionUID = 1L;

  /** 手机号 */
  @Schema(title = "手机号")
  private String mobile;

  /** 邮箱 */
  @Schema(title = "邮箱")
  private String email;

  /** 用户昵称 */
  @Schema(title = "用户昵称")
  private String nickname;

  /** 密码 */
  @Schema(title = "密码")
  private String password;

  /** 头像 */
  @Schema(title = "头像")
  private String avatar;

  /** 帐号状态（1正常 2停用 3冻结） */
  @Schema(title = "帐号状态（1正常 2停用 3冻结）")
  private Integer status;

  /** 最后登录IP */
  @Schema(title = "最后登录IP")
  private String lastLoginIp;

  /** 最后登录时间 */
  @Schema(title = "最后登录时间")
  @JsonFormat(pattern = DatePattern.NORM_DATETIME_PATTERN)
  private LocalDateTime lastLoginTime;

  /** 角色id */
  @Schema(title = "角色id")
  private Long roleId;

  @Column(ignore = true)
  @Schema(title = "token")
  private String accessToken;

  public void changePwd(String password) {
    if (StrUtil.isNotEmpty(password)) {
      this.setPassword(DigestUtil.bcrypt(password));
    }
  }

  public void statusCheck() {
    USER_STATUS_LOCK_ERROR.notEquals(getStatus(), 2);
    USER_STATUS_FREEZE_ERROR.notEquals(getStatus(), 3);
    USER_STATUS_ERROR.equals(getStatus(), 1);
  }
}
